package com.asiainfo.lop;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.asiainfo.lop.net.VolleyInterface;
import com.asiainfo.lop.net.VolleyRequest;
import com.asiainfo.lop.os.InitParam;
import com.asiainfo.lop.util.CryptionUtil;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.util.List;

@EActivity
public class CameraActivity extends BaseActivity {
    @ViewById(R.id.self_loc)
    TextView selflocTv;

    @ViewById(R.id.info)
    LinearLayout infoLayout;

    @ViewById(R.id.info_simple)
    TextView infoSimpleTv;

    @ViewById(R.id.info_detail)
    TextView infoDetailTv;

    @ViewById(R.id.info_close)
    ImageView infoCloseIv;

    JSONObject curInfo;


    private Camera camera;
    private SurfaceHolder holder;

    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//拍照过程屏幕一直处于高亮
        //设置手机屏幕朝向，一共有7种
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //SCREEN_ORIENTATION_BEHIND： 继承Activity堆栈中当前Activity下面的那个Activity的方向
        //SCREEN_ORIENTATION_LANDSCAPE： 横屏(风景照) ，显示时宽度大于高度
        //SCREEN_ORIENTATION_PORTRAIT： 竖屏 (肖像照) ， 显示时高度大于宽度
        //SCREEN_ORIENTATION_SENSOR  由重力感应器来决定屏幕的朝向,它取决于用户如何持有设备,当设备被旋转时方向会随之在横屏与竖屏之间变化
        //SCREEN_ORIENTATION_NOSENSOR： 忽略物理感应器——即显示方向与物理感应器无关，不管用户如何旋转设备显示方向都不会随着改变("unspecified"设置除外)
        //SCREEN_ORIENTATION_UNSPECIFIED： 未指定，此为默认值，由Android系统自己选择适当的方向，选择策略视具体设备的配置情况而定，因此不同的设备会有不同的方向选择
        //SCREEN_ORIENTATION_USER： 用户当前的首选方向

        setContentView(R.layout.lar_main);

        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        holder = surfaceView.getHolder();
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        holder.setFixedSize(176, 164);

        holder.addCallback(new SurfaceViewCallback());
    }

    private final class SurfaceViewCallback implements android.view.SurfaceHolder.Callback {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            camera = Camera.open(0); //默认启用的摄像头是后置摄像头id=0，  id =1前置摄像头

            try {
                camera.setPreviewDisplay(holder);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Camera.Parameters parameters = camera.getParameters();


            setCameraDisplayOrientation(CameraActivity.this, 0, camera);
            /* 设置预览照片的大小，此处设置为全屏 */
            WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE); // 获取当前屏幕管理器对象
            Display display = wm.getDefaultDisplay();                           // 获取屏幕信息的描述类
            /* 每秒从摄像头捕获5帧画面， */
            parameters.setPreviewFrameRate(5);
            /* 设置照片的输出格式:jpg */
            parameters.setPictureFormat(PixelFormat.JPEG);
            /* 照片质量 */
            parameters.set("jpeg-quality", 85);
            /* 设置照片的大小：此处照片大小等于屏幕大小 */
            /* 将参数对象赋予到 camera 对象上 */
//            camera.setParameters(parameters);
            camera.startPreview();
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            if (camera != null) {
                camera.release();
            }
        }

    }

    public static void setCameraDisplayOrientation(Activity activity,
                                                   int cameraId, android.hardware.Camera camera) {
        android.hardware.Camera.CameraInfo info =
                new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;   // compensate the mirror
        } else {   // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }

    @AfterViews
    void initGps() {
        selflocTv.setBackgroundColor(Color.argb(120, 0, 0, 0)); //背景透明度
        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);    //注册监听函数
        initLocation();
        mLocationClient.start();
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        option.setScanSpan(1000 * 10);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        option.setNeedDeviceDirect(true);
        mLocationClient.setLocOption(option);
    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            int errorCode = location.getLocType();
            if (161 == errorCode) {
                double lat = location.getLatitude();
                double lng = location.getLongitude();
                String address = location.getAddrStr();
                float direction = location.getDirection();
                selflocTv.setText("当前位置：" + address);
                queryLoc(lng + "", lat + "", "50", direction);
            } else {
                Toast.makeText(CameraActivity.this, "获取位置失败", Toast.LENGTH_LONG).show();
            }

            //Receive Location
            StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            sb.append(location.getTime());
            sb.append("\nerror code : ");
            sb.append(location.getLocType());
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());// 单位：公里每小时
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\nheight : ");
                sb.append(location.getAltitude());// 单位：米
                sb.append("\ndirection : ");
                sb.append(location.getDirection());// 单位度
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\ndescribe : ");
                sb.append("gps定位成功");

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                //运营商信息
                sb.append("\noperationers : ");
                sb.append(location.getOperators());
                sb.append("\ndescribe : ");
                sb.append("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());// 位置语义化信息
            List<Poi> list = location.getPoiList();// POI数据
            if (list != null) {
                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }
//            Toast.makeText(CameraActivity.this, sb.toString(), Toast.LENGTH_LONG).show();
        }
    }

    private void queryLoc(String lng, String lat, String alt, float direction) {
        lng = CryptionUtil.encryptWebParam(lng);
        lat = CryptionUtil.encryptWebParam(lat);
        alt = CryptionUtil.encryptWebParam(alt);

        String url = getString(R.string.rest_url_rooturl) + getString(R.string.rest_url_lar_queryloc);
        url = url.replace("{lng}", lng);
        url = url.replace("{lat}", lat);
        url = url.replace("{alt}", alt);

        VolleyInterface volleyInterface = new VolleyInterface(this) {
            @Override
            public void success(JSONObject result) {
                JSONArray datas = result.getJSONArray("data");
                for (int i = 0; i < datas.size(); i++) {
                    JSONObject data = datas.getJSONObject(i);
                    if (false) {
                        curInfo = data;
                        break;
                    }
                }

                int r = (int) Math.floor(Math.random() * datas.size()) + 1;
                curInfo = datas.getJSONObject(r);
                String simpleDesc = curInfo.getString("simpleDesc");
                String detailDesc = curInfo.getString("detailDesc");
                if(StringUtils.isNotBlank(simpleDesc) && StringUtils.isNotBlank(detailDesc)){
                    infoSimpleTv.setText(simpleDesc);
                    infoDetailTv.setText(detailDesc);
                    infoLayout.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void error(VolleyError volleyError) {
                Log.e(InitParam.TAG, volleyError.getMessage());
            }
        };
        VolleyRequest.get(this, url, "CameraActivity", volleyInterface);
    }

    @Click(R.id.info)
    void showDetail() {
        infoSimpleTv.setVisibility(View.GONE);
        infoDetailTv.setVisibility(View.VISIBLE);
    }

    @Click(R.id.info_close)
    void closeInfo() {
        infoLayout.setVisibility(View.GONE);
    }
}

